package com.xoms.pad.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xoms.pad.aspect.datasource.DataSourceSwitcher;
import com.xoms.pad.controller.res.bean.RProCategory3Bean;
import com.xoms.pad.controller.res.bean.RProCategoryJSONBean;
import com.xoms.pad.controller.res.bean.RProductBean;
import com.xoms.pad.model.AccountBean;
import com.xoms.pad.model.ProCategory3Bean;
import com.xoms.pad.model.ProCategoryBean;
import com.xoms.pad.model.ProductBean;
import com.xoms.pad.persist.dao.ProCategoryDao;
import com.xoms.pad.persist.dao.ProductDao;
import com.xoms.pad.service.ProCategoryService;
import com.xoms.util.StringUtil;

@Service
public class ProCategoryServiceImpl implements ProCategoryService {

	Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	ProCategoryDao proCategoryImpl;
	
	@Autowired
	ProductDao productDao;

	@Override
	public RProCategoryJSONBean getAllCategories(AccountBean account) {
		RProCategoryJSONBean bean = new RProCategoryJSONBean();
		JSONArray jsonArray = new JSONArray();
		// 从缓存获取所有分类
		String cateStr = null;// proCategoryCacheImpl.getAllCategoresCache();
		if (StringUtil.isEmpty(cateStr)) {// redis内分类信息为空则从数据库查询分类
			// 手动切换数据源
			DataSourceSwitcher.setDataSourceType(DataSourceSwitcher.DATA_SOURCE_HQ);
			List<ProCategoryBean> cates = proCategoryImpl.selectAllCates();
			// 手动切换数据源
			/*DataSourceSwitcher.setDataSourceType(DataSourceSwitcher.DATA_SOURCE_XOMS);
			List<ProCategoryBean> cate2s = proCategoryImpl.selectAllCates();*/
			if (cates == null) {
				return null;
			}
			
			logger.info("cates57分类：" + JSON.toJSONString(cates));
			// 构造根节点
			ProCategoryBean root = new ProCategoryBean();
			root.setCid("0");
			cates.add(root);
			// 根据父节点id分组
			Map<String, List<ProCategoryBean>> map = cates.stream().filter(o -> Objects.nonNull(o.getParentId()))
					.collect(Collectors.groupingBy(ProCategoryBean::getParentId));

			// 循环处理子节点 构建树状结构
			cates.forEach(proCategory -> {
				if (map.containsKey(proCategory.getCid())) {
					proCategory.setSubCategories(map.get(proCategory.getCid()));
				}
			});
			// 获取根节点下的所有服务项
			ProCategoryBean result = cates.stream().filter(proCategory -> "0".equals(proCategory.getCid())).findFirst()
					.orElse(null);
			String catesJson = JSON.toJSONString(result.getSubCategories());
			logger.info("cates76分类：" + catesJson);
			jsonArray = JSON.parseArray(catesJson);
			// 将分类存入缓存
			// proCategoryCacheImpl.setAllCategoryCache(catesJson);
		} else {
			jsonArray = JSON.parseArray(cateStr);
		}
		bean.setCategory(jsonArray);
		return bean;
	}

	/* (non-Javadoc)
	 * @see com.xoms.pad.service.ProCategoryService#getCate3Product(com.xoms.pad.model.AccountBean, java.lang.String)
	 */
	@Override
	public List<RProCategory3Bean> getCate3Product(String accid,String categoryId) {

		DataSourceSwitcher.setDataSourceType(DataSourceSwitcher.DATA_SOURCE_XOMS);
		List<ProCategory3Bean> cates = proCategoryImpl.getCate3ProductByCate2(categoryId);
		if (cates == null) {
			return null;
		}
			
		List<RProCategory3Bean> bean = new ArrayList<RProCategory3Bean>();
		RProCategory3Bean rProCategory3Bean;
		for(ProCategory3Bean proCategory3Bean:cates){
			rProCategory3Bean = new RProCategory3Bean();
			rProCategory3Bean.setCid(proCategory3Bean.getCid());
			rProCategory3Bean.setName(proCategory3Bean.getName());
			rProCategory3Bean.setParentId(proCategory3Bean.getParentId());
			rProCategory3Bean.setLevel(proCategory3Bean.getLevel());
			rProCategory3Bean.setIsHq(proCategory3Bean.getIsHq());
			rProCategory3Bean.setSort(proCategory3Bean.getSort());
			rProCategory3Bean.setCreateTime(proCategory3Bean.getCreateTime());
			rProCategory3Bean.setAccountId(proCategory3Bean.getAccountId());
			
			String cid = proCategory3Bean.getCid(); //三级分类
			//获取数据源
			DataSourceSwitcher.setDataSourceType(DataSourceSwitcher.DATA_SOURCE_XOMS);
			List<ProductBean> productList = productDao.selectList(accid,cid);
			List<RProductBean> products = new ArrayList<>();
			for(ProductBean product: productList){
				RProductBean rProductBean = new RProductBean();
				rProductBean.setPid(product.getPid());
				rProductBean.setName(product.getName());
				rProductBean.setCreateTime(product.getCreateTime());
				rProductBean.setProductNo(product.getProductNo());
				rProductBean.setProductBar(product.getProductBar());
				rProductBean.setCategoryId(product.getCategoryId());
				rProductBean.setCategoryArr(product.getCategoryArr());
				rProductBean.setImgUrl(product.getImgUrl());
				rProductBean.setSpecs(product.getSpecs());
				rProductBean.setUnit(product.getUnit());
				rProductBean.setUnitId(product.getUnitId());
				rProductBean.setPrice(product.getPrice());
				rProductBean.setRemark(product.getRemark());
				rProductBean.setSaleStatus(product.getSaleStatus());
				rProductBean.setStartTime(product.getStartTime());
				rProductBean.setEndTime(product.getEndTime());
				rProductBean.setAntiPrice(product.getAntiPrice());
				rProductBean.setInitial(product.getInitial());
				rProductBean.setMaxNum(product.getMaxNum());
				rProductBean.setWarnNum(product.getWarnNum());
				rProductBean.setStore(product.getStore());
				products.add(rProductBean);
			}
			rProCategory3Bean.setProducts(products);
			
			
			bean.add(rProCategory3Bean);
		}
			
		return bean;
	}

}
